package com.xz.web.controller.purchase;

import com.xz.common.annotation.Log;
import com.xz.common.core.controller.BaseController;
import com.xz.common.core.domain.AjaxResult;
import com.xz.common.core.page.TableDataInfo;
import com.xz.common.enums.BusinessType;
import com.xz.common.utils.RedisCode;
import com.xz.common.utils.poi.ExcelUtil;
import com.xz.purchase.domain.Purchase;
import com.xz.purchase.domain.PurchaseProduct;
import com.xz.purchase.dto.PurchaseDto;
import com.xz.purchase.dto.PurchaseImportVo;
import com.xz.purchase.dto.PurchaseProductImportDto;
import com.xz.purchase.service.IPurchaseImportService;
import com.xz.purchase.service.IPurchaseProductService;
import com.xz.purchase.service.IPurchaseService;
import com.xz.purchase.vo.*;
import com.xz.supplierContract.domain.SupplierContract;
import com.xz.supplierContract.service.ISupplierContractService;
import com.xz.warehouse.domain.Warehouse;
import com.xz.warehouse.dto.WarehouseDto;
import com.xz.warehouse.service.IWarehouseService;
import common.ECDateUtils;
import common.ECUuidGenUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.validation.Valid;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 采购Controller
 *
 * @author xz
 * @date 2024-01-06
 */
@RestController
@RequestMapping("/purchase/purchase")
public class PurchaseController extends BaseController {
    @Autowired
    private IPurchaseService purchaseService;
    @Autowired
    private IPurchaseProductService purchaseProductService;
    @Autowired
    private IWarehouseService warehouseService;
    @Autowired
    private ISupplierContractService supplierContractService;
    @Autowired
    private IPurchaseImportService purchaseImportService;
    /**
     * 查询采购列表
     */
    //@PreAuthorize("@ss.hasPermi('purchase:purchase:list')")
    @GetMapping("/list")
    public TableDataInfo list(Purchase purchase) {
        startPage();
        List<PurchaseDto> list = purchaseService.selectPurchaseList(purchase);
        return getDataTable(list);
    }
    /**
     * 进销存统计
     */
    //@PreAuthorize("@ss.hasPermi('purchase:purchase:list')")
    @GetMapping("/purchaseStatistics")
    public TableDataInfo purchaseStatistics(Purchase purchase) {
        startPage();
        List<PurchaseStatisticsVo> purchaseStatisticsVoList = purchaseService.purchaseStatistics(purchase);
        return getDataTable(purchaseStatisticsVoList);
    }

    /**
     * 进销存统计
     */
    @GetMapping("/exportPurchaseStatistics")
    public AjaxResult exportPurchaseStatistics(Purchase purchase) {

        List<PurchaseStatisticsVo> purchaseStatisticsVoList = purchaseService.purchaseStatistics(purchase);
        ExcelUtil<PurchaseStatisticsVo> util = new ExcelUtil<PurchaseStatisticsVo>(PurchaseStatisticsVo.class);
        return util.exportExcel(purchaseStatisticsVoList, "进销存统计");
    }

    /**
     * 导出采购列表
     */
    //@PreAuthorize("@ss.hasPermi('purchase:purchase:export')")
    @Log(title = "采购", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(Purchase purchase) {
        List<PurchaseDto> list = purchaseService.selectPurchaseList(purchase);
        ExcelUtil<PurchaseDto> util = new ExcelUtil<PurchaseDto>(PurchaseDto.class);
        return util.exportExcel(list, "采购数据");
    }

    /**
     * 采购导入
     */
    //@PreAuthorize("@ss.hasPermi('purchase:purchase:add')")
    @Log(title = "采购导入", businessType = BusinessType.IMPORT)
    @PostMapping("/importExcelNew")
    public AjaxResult importExcelNew(@RequestParam("file") MultipartFile file) throws Exception {
        ExcelUtil<PurchaseProductImportDto> util = new ExcelUtil<PurchaseProductImportDto>(PurchaseProductImportDto.class);
        List<PurchaseProductImportDto> list = util.importExcel(file.getInputStream());
        // 此次系统批量入库的批次号
        String batchStorageNumber = RedisCode.getCode("PLRK");
        // 开始入库
        List<PurchaseProductImportDto> importFailedDtos = purchaseImportService.importExcel(batchStorageNumber,list);
        // 如果有导入失败的数据，那就导出excel，供前端下载
        if(CollectionUtils.isEmpty(importFailedDtos)){
            return AjaxResult.success("采购入库-导入成功！");
        }
        AjaxResult excelResult = util.exportExcel(importFailedDtos,
                "采购入库-导入失败 " + ECDateUtils.getCurrentDate(ECDateUtils.FormatTime_s));
        AjaxResult result = AjaxResult.success("采购入库-导入失败！");
        result.put("failExcel",excelResult.get("msg"));
        return result;
    }

    /**
     * 获取采购详细信息
     */
    //@PreAuthorize("@ss.hasPermi('purchase:purchase:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id) {
        return AjaxResult.success(purchaseService.selectPurchaseById(id));
    }
    /**
     * 导入库存商品
     */
    @Log(title = "导入库存商品", businessType = BusinessType.EXPORT)
    @PostMapping("/importExcel")
    public AjaxResult importExcel(@RequestParam("file") MultipartFile file) throws Exception {
        ExcelUtil<PurchaseImportVo> util = new ExcelUtil<PurchaseImportVo>(PurchaseImportVo.class);
        List<PurchaseImportVo> list = util.importExcel(file.getInputStream(),1);
        AjaxResult message = purchaseService.importExcel(list);
        return message;
    }
    /**
     * 新增采购
     */
    //@PreAuthorize("@ss.hasPermi('purchase:purchase:add')")
    @Log(title = "采购", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@Valid @RequestBody Purchase purchase) {
        return purchaseService.insertPurchase(purchase);
    }

    /**
     * 修改采购
     */
    //@PreAuthorize("@ss.hasPermi('purchase:purchase:edit')")
    @Log(title = "采购", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@Valid @RequestBody Purchase purchase) {
        return purchaseService.updatePurchase(purchase);
    }

    /**
     * 删除采购
     */
    //@PreAuthorize("@ss.hasPermi('purchase:purchase:remove')")
    @Log(title = "采购", businessType = BusinessType.DELETE)
    @DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids) {
        return toAjax(purchaseService.deletePurchaseByIds(ids));
    }
    /**
     * 作废
     */
    //@PreAuthorize("@ss.hasPermi('purchase:purchase:remove')")
    @Log(title = "采购", businessType = BusinessType.DELETE)
    @DeleteMapping("/delete/{id}")
    public AjaxResult delete(@PathVariable Long id) {
        return toAjax(purchaseService.deletePurchaseById(id));
    }
    /**
     * 冲红
     */
    @PostMapping("/blush")
    public AjaxResult blush(@Valid @RequestBody BlushVo blushVo) {
        return purchaseService.blush(blushVo);
    }

    @GetMapping("/chooseProductList")
    public TableDataInfo chooseProductList(PurchaseProduct purchaseProduct) {
        startPage();
        //普通查
        List<ProductVo> productVos = purchaseProductService.chooseProductList(purchaseProduct);
        return getDataTable(productVos);
    }

    @GetMapping("/entSupplier/chooseProductList")
    public TableDataInfo chooseProductListForEntSupplier(PurchaseProduct purchaseProduct) {
      // 兼容贸易中间商的商品选择的业务
      if(null != purchaseProduct.getEntSupplierId()){
        // 前端传入贸易中间商id时，需要去获取最新的合同。
        SupplierContract contract = supplierContractService.selectCurrentBySupplierId(purchaseProduct.getEntSupplierId());
        if(null != contract){
          //放入合同id
          purchaseProduct.setEntContractId(contract.getId());
          //启用分页
          startPage();
          //开始查询商品分页数据
          List<ProductVo> productVos = purchaseProductService.chooseProductListForSupplier(purchaseProduct);
          //返回结果
          return getDataTable(productVos);
        }
      }
      //非正常查询，一律则默认返回空集合，
      return getDataTable(new ArrayList<>());
    }

  /**
   * 诊疗开单新增药品专用
   * @param purchaseProduct
   * @return
   */
    @GetMapping("/chooseProductForDiagnosisae")
    public TableDataInfo chooseProductForDiagnosisae(PurchaseProduct purchaseProduct) {
      startPage();
      List<ChoosePurchaseProductVo> productVos = purchaseProductService.chooseProductForDiagnosisae(purchaseProduct);
      if(!CollectionUtils.isEmpty(productVos)){
        productVos.forEach(data->{
          data.setTempId(ECUuidGenUtils.genUUID());
        });
      }
      return getDataTable(productVos);
    }

    @GetMapping("/choosePurchaseProductList")
    public TableDataInfo choosePurchaseProductList(PurchaseProduct purchaseProduct) {
        Warehouse warehouse =new Warehouse();
        warehouse.setStatus("0");
        List<WarehouseDto> warehouseList = warehouseService.getWarehouseList(warehouse);
        if(CollectionUtils.isEmpty(warehouseList)){
            List<ProductVo> productVos = new ArrayList<>();
            getDataTable(productVos);
        }
        List<Long> warehouseIdList = warehouseList.stream().map(WarehouseDto::getId).distinct().collect(Collectors.toList());
        purchaseProduct.setWarehouseIdList(warehouseIdList);
        startPage();
        List<ProductVo> productVos = purchaseProductService.choosePurchaseProductList(purchaseProduct);
        return getDataTable(productVos);
    }

    /**
     * 即使库存--商品纬度
     */
    @GetMapping("/commodityDimensionStatisticsList")
    public TableDataInfo commodityDimensionStatisticsList(PurchaseProduct purchase) {
        startPage();
        List<CommodityDimensionStatisticsVo> statisticsVoList = purchaseService.commodityDimensionStatisticsList(purchase);
        return getDataTable(statisticsVoList);
    }
    /**
     * 导出即使库存--商品纬度
     */
    @GetMapping("/commodityDimensionStatisticsExport")
    public AjaxResult commodityDimensionStatisticsExport(PurchaseProduct purchase) {
        List<CommodityDimensionStatisticsVo> list = purchaseService.commodityDimensionStatisticsList(purchase);
        ExcelUtil<CommodityDimensionStatisticsVo> util = new ExcelUtil<CommodityDimensionStatisticsVo>(CommodityDimensionStatisticsVo.class);
        return util.exportExcel(list, "商品纬度即使库存数据");
    }
    /**
     * 即使库存--批次纬度
     */
    @GetMapping("/batchDimensionStatisticsList")
    public TableDataInfo batchDimensionStatisticsList(PurchaseProduct purchase) {
        startPage();
        List<BatchDimensionStatisticsVo> statisticsVoList = purchaseService.batchDimensionStatistics(purchase);
        return getDataTable(statisticsVoList);
    }
    /**
     * 导出即使库存--批次纬度
     */
    @GetMapping("/batchDimensionStatisticsExport")
    public AjaxResult batchDimensionStatisticsExport(PurchaseProduct purchase) {
        List<BatchDimensionStatisticsVo> list = purchaseService.batchDimensionStatistics(purchase);
        ExcelUtil<BatchDimensionStatisticsVo> util = new ExcelUtil<BatchDimensionStatisticsVo>(BatchDimensionStatisticsVo.class);
        return util.exportExcel(list, "批次纬度即使库存数据");
    }
    /**
     * 即使库存--财务纬度
     */
    @GetMapping("/billDimensionStatisticsList")
    public TableDataInfo billDimensionStatisticsList(PurchaseProduct purchase) {
        startPage();
        List<BillDimensionStatisticsVo> statisticsVoList = purchaseService.billDimensionStatisticsList(purchase);
        return getDataTable(statisticsVoList);
    }
    /**
     * 导出即使库存--财务纬度
     */
    @GetMapping("/billDimensionStatisticsExport")
    public AjaxResult billDimensionStatisticsExport(PurchaseProduct purchase) {
        List<BillDimensionStatisticsVo> list = purchaseService.billDimensionStatisticsList(purchase);
        ExcelUtil<BillDimensionStatisticsVo> util = new ExcelUtil<BillDimensionStatisticsVo>(BillDimensionStatisticsVo.class);
        return util.exportExcel(list, "财务纬度即使库存数据");
    }
    /**
     * 采购入库
     */
    @PostMapping("/purchaseWarehousing")
    public AjaxResult purchaseWarehousing(@Valid @RequestBody Purchase purchase) {
        return purchaseService.purchaseWarehousing(purchase);
    }

    /**
     *  有效期预警
     */
    @GetMapping("/validityProductList")
    public TableDataInfo validityProductList(PurchaseProduct purchase) {
        startPage();
        List<PurchaseProduct> purchaseProducts = purchaseProductService.validityProductList(purchase);
        return getDataTable(purchaseProducts);
    }
    /**
     * 导出有效期预警
     */
    @GetMapping("/validityProductListExport")
    public AjaxResult validityProductListExport(PurchaseProduct purchase) {
        List<PurchaseProduct> purchaseProducts = purchaseProductService.validityProductList(purchase);
        ExcelUtil<PurchaseProduct> util = new ExcelUtil<PurchaseProduct>(PurchaseProduct.class);
        return util.exportExcel(purchaseProducts, "效期预警数据");
    }

}
